//
//  NewLoveMarketTimeFilterView.m
//  HCNewGoldFinger
//
//  Created by 刘琛 on 2018/8/1.
//  Copyright © 2018年 zjhcsoftios. All rights reserved.
//

#import "NewLoveMarketTimeFilterView.h"
#import "DatePickerView.h"
#import "ZSBSearchModel.h"
#import "UIColor+Ex.h"
#import "SVProgressHUD.h"

@interface NewLoveMarketTimeFilterView()

@property (nonatomic, strong) NSMutableArray *dataList;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;


@property (weak, nonatomic) IBOutlet UIButton *moreTime;
@property (weak, nonatomic) IBOutlet UIButton *startTimeButton;
@property (weak, nonatomic) IBOutlet UIButton *endTimeButton;

@property (nonatomic, strong) NSDate *startTime;
@property (nonatomic, strong) NSDate *endTime;

//右侧选中按钮
@property (nonatomic, strong) UIButton *selectedButton;
//左侧选中按钮
@property (nonatomic, strong) UIButton *timeTypeSelectedButton;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topOffset;

@property (copy, nonatomic) NewLoveMarketTimeFilterViewFailureBlock fail;
@property (copy, nonatomic) NewLoveMarketTimeFilterViewSuccessBlock success;

@end

@implementation NewLoveMarketTimeFilterView

+ (void)showNewLoveMarketTimeFilterViewInView:(UIView *)view
                                timeFiterList:(NSMutableArray *) timeFiterList
                                      success:(NewLoveMarketTimeFilterViewSuccessBlock)success
                                      failure:(NewLoveMarketTimeFilterViewFailureBlock)fail {
    
    NewLoveMarketTimeFilterView *timeFilterView = [[[NSBundle bundleWithURL:[[NSBundle bundleForClass:[self class]] URLForResource:@"NewMarketLib" withExtension:@"bundle"]] loadNibNamed:@"NewLoveMarketTimeFilterView" owner:nil options:nil] firstObject];
    timeFilterView.frame = view.bounds;
    timeFilterView.dataList = timeFiterList;
    timeFilterView.success = success;
    timeFilterView.fail = fail;

    [view addSubview:timeFilterView];
    
}

+ (void)showNewLoveMarketTimeFilterView:(UIView *)view point:(CGPoint)point timeFiterList:(NSMutableArray *)timeFiterList success:(NewLoveMarketTimeFilterViewSuccessBlock)success failure:(NewLoveMarketTimeFilterViewFailureBlock)fail  {
    
    
    NewLoveMarketTimeFilterView *timeFilterView = [[[NSBundle bundleWithURL:[[NSBundle bundleForClass:[self class]] URLForResource:@"NewMarketLib" withExtension:@"bundle"]] loadNibNamed:@"NewLoveMarketTimeFilterView" owner:nil options:nil] firstObject];
    timeFilterView.topOffset.constant = point.y;
    timeFilterView.frame = view.bounds;
    timeFilterView.dataList = timeFiterList;
    timeFilterView.success = success;
    timeFilterView.fail = fail;
    
    [view addSubview:timeFilterView];
}


- (void)awakeFromNib {
    [super awakeFromNib];
    
//    NSArray *temp = [NSArray arrayWithObjects:@"派单时间",@"接单时间",@"转派时间",@"回单时间", nil];
    
    //按钮tag 1-6为时间选择 7为更多时间 8-9为开始时间结束时间

    for (int i = 1; i <= 9; i++) {
        UIButton *button = [self viewWithTag:i];
        [self buttonInit:button];
        if (i <= 7) {
            [button addTarget:self action:@selector(timeSelectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        }else {
            [button addTarget:self action:@selector(startTimeButtonOrEndButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    
    _dataList = [NSMutableArray array];
    
    
}


- (void)setDataList:(NSMutableArray *)dataList {
    
    _dataList = dataList;
    
    NSInteger leftButtonCount = _dataList.count;
    
    _scrollView.contentSize = CGSizeMake(75, leftButtonCount * 30 + (leftButtonCount - 1) * 15);
    for (int i = 0; i < leftButtonCount; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0 + (15 + 30) * i, 75, 30)];
        [self buttonInit:button];
        ZSBSearchModel *model = _dataList[i];
        button.tag = 100 + i;
        [button setTitle:model.name forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button setTitleColor:[UIColor colorWithHexString:@"999999"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(timeTypeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_scrollView addSubview:button];
    }
    
    [self setStartTimeButtonAndEndTimeButtonRest];
    [self allTimeSelectButtonStateRest];
}

//按钮初始化
- (void)buttonInit:(UIButton *) button {
    button.layer.cornerRadius = 3;
    button.layer.borderWidth = 1;
    button.layer.borderColor = [UIColor colorWithHexString:@"CCCCCC"].CGColor;
}

//右边按钮全部还原
- (void)allTimeSelectButtonStateRest {
    for (int i = 1; i <= 7; i++) {
        UIButton *button = [self viewWithTag:i];
        [self setTimeSelectButtonStateRest:button];
    }
    _selectedButton = [[UIButton alloc] init];
    [self setStartTimeButtonAndEndTimeButtonRest];
}

// 右边按钮状态变成未选中样式
- (void)setTimeSelectButtonStateRest:(UIButton *) button {
    button.layer.borderColor = [UIColor colorWithHexString:@"CCCCCC"].CGColor;
    button.backgroundColor = [UIColor whiteColor];
    [button setTitleColor:[UIColor colorWithHexString:@"999999"] forState:UIControlStateNormal];
}

// 右边按钮状态变成选中样式
- (void)setTimeSelectButtonStateSelect:(UIButton *) button {
    button.layer.borderColor = [UIColor colorWithHexString:@"169BD5"].CGColor;
    button.backgroundColor = [UIColor colorWithHexString:@"169BD5"];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}

// 开始时间 结束时间 按钮归零
- (void)setStartTimeButtonAndEndTimeButtonRest {
    self.startTimeButton.hidden = YES;
    [self.startTimeButton setTitle:@"开始时间" forState:UIControlStateNormal];
    self.startTime = [[NSDate alloc] init];
    
    self.endTimeButton.hidden = YES;
    [self.endTimeButton setTitle:@"结束时间" forState:UIControlStateNormal];
    self.endTime = [[NSDate alloc] init];
}


//tag 1-7按钮点击事件
- (void)timeSelectButtonAction:(UIButton *) button {
    
    if (_timeTypeSelectedButton) {
        
        if (_selectedButton.tag != button.tag) {
            
            if (_selectedButton) {
                [self setTimeSelectButtonStateRest:_selectedButton];
                
            }
            _selectedButton = button;
            
            [self setTimeSelectButtonStateSelect:button];
            
            if (button.tag == 7) {
                _startTimeButton.hidden = NO;
                _endTimeButton.hidden = NO;
            }else {
                if (self.startTimeButton.hidden == NO) {
                    [self setStartTimeButtonAndEndTimeButtonRest];
                }
            }
        }
    }else {
        [SVProgressHUD showErrorWithStatus:@"请选择一个时间状态"];
    }
    
    
}

//左侧时间类型点击事件
- (void)timeTypeButtonAction:(UIButton *) button {
    
    if (_timeTypeSelectedButton.tag != button.tag) {
        if (_timeTypeSelectedButton) {
            
            [self setTimeSelectButtonStateRest:_timeTypeSelectedButton];
            
        }
        
        _timeTypeSelectedButton = button;
        
        [self setTimeSelectButtonStateSelect:button];
        
        [self allTimeSelectButtonStateRest];
        
        ZSBSearchModel *model = _dataList[button.tag - 100];
        for (int i = 1; i < 7; i++) {
            UIButton *button = [self viewWithTag:i];
            if (i <= [model.count intValue]) {
                button.hidden = NO;
            }else {
                button.hidden = YES;
            }
        }
        if (_moreTime.hidden) {
            _moreTime.hidden = NO;
        }
    }
    
    
}

// 开始时间 或者 结束时间点击
- (void)startTimeButtonOrEndButtonAction:(UIButton *) button {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：zzz表示时区
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    [DatePickerView showDatePickerInView:self.window miniDate:@"2017-01-01" maxDate:[dateFormatter stringFromDate:[[NSDate alloc] init]] success:^(NSDate *date) {
        
        //开始时间按钮点击
        if (button.tag == 8) {
            //判断是否有结束时间
            if (![self.endTimeButton.titleLabel.text isEqualToString:@"结束时间"]) {
                //比较选择的时间 晚于结束时间
                if ([date laterDate:_endTime] == date ) {
                    if ([[dateFormatter stringFromDate:date] isEqualToString:[dateFormatter stringFromDate:_endTime]]) {
                        self.startTime = date;
                    }else {
                        
                        [SVProgressHUD showErrorWithStatus:@"开始时间必须早于结束时间"];
                        return;
                    }
                }else {
                    
                    self.startTime = date;
                    
                }
                
                
            }else {
                self.startTime = date;
            }
            
            //结束时间按钮点击
        }else if (button.tag == 9) {
            //判断是否有开始时间
            if (![self.startTimeButton.titleLabel.text isEqualToString:@"开始时间"]) {
                //选择的时间 早于开始时间
                if ([date earlierDate:self.startTime] == date ) {
                    if ([[dateFormatter stringFromDate:date] isEqualToString:[dateFormatter stringFromDate:self.startTime]]) {
                        
                        self.endTime = date;
                        
                    }else {
                        
                        [SVProgressHUD showErrorWithStatus:@"开始时间必须早于结束时间"];
                        return;
                    }
                }else {
                    
                    self.endTime = date;
                    
                }
                
            }else {
                self.endTime = date;
            }
            
        }
        
        
        [button setTitle:[dateFormatter stringFromDate:date] forState:UIControlStateNormal];
    
    
    } failure:^{
        
    }];
    

}

//获取昨天
- (NSString *)getYesterday {
    
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:( NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ) fromDate:[[NSDate alloc] init]];
    
    NSDate *today = [[NSDate alloc] init];
    
    [components setHour:-24];
    [components setMinute:0];
    [components setSecond:0];
    NSDate *yesterday = [cal dateByAddingComponents:components toDate: today options:0];
    
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString *s = [NSString stringWithFormat:@"%@=%@", [myDateFormatter stringFromDate:yesterday],[myDateFormatter stringFromDate:yesterday]];
    return s;
}

//获取N天内
- (NSString *)getFromBeginDayToTodayWith:(NSInteger ) days {
    
    
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:( NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ) fromDate:[[NSDate alloc] init]];
    
    NSDate *today = [[NSDate alloc] init];
    
    [components setHour:-24 * days];
    [components setMinute:0];
    [components setSecond:0];
    NSDate *beginDay = [cal dateByAddingComponents:components toDate: today options:0];
    
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString *s = [NSString stringWithFormat:@"%@=%@", [myDateFormatter stringFromDate:beginDay], [myDateFormatter stringFromDate:today]];
    return s;
}

//获取上一个月的第一天和最后一天
- (NSString *)getLastMonthBeginAndEnd {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:( NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ) fromDate:[[NSDate alloc] init]];
    
    NSDate *today = [[NSDate alloc] init];
    
    [components setMonth:-1];
    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];
    NSDate *beginDay = [cal dateByAddingComponents:components toDate: today options:0];
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString *s = [self getMonthBeginAndEndWith:[myDateFormatter stringFromDate:beginDay]];
    return s;
}

//获取指定定月的第一天和最后一天
- (NSString *)getMonthBeginAndEndWith:(NSString *)dateStr{
    
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"YYYY-MM-dd"];
    NSDate *newDate=[format dateFromString:dateStr];
    double interval = 0;
    NSDate *beginDate = nil;
    NSDate *endDate = nil;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    [calendar setFirstWeekday:2];//设定周一为周首日
    BOOL ok = [calendar rangeOfUnit:NSMonthCalendarUnit startDate:&beginDate interval:&interval forDate:newDate];
    //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
    if (ok) {
        endDate = [beginDate dateByAddingTimeInterval:interval-1];
    }else {
        return @"";
    }
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *beginString = [myDateFormatter stringFromDate:beginDate];
    NSString *endString = [myDateFormatter stringFromDate:endDate];
    NSString *s = [NSString stringWithFormat:@"%@=%@",beginString,endString];
    return s;
}


//取消按钮点击
- (IBAction)cannelButtonAction:(id)sender {
    self.fail();
    [self removeFromSuperview];
}

//确定按钮点击
- (IBAction)confrimButtonAction:(id)sender {
    
    if (_timeTypeSelectedButton.tag != 0) {
        
        if (_selectedButton.tag != 0) {
            
            switch (_selectedButton.tag) {
                case 1:
                {
                    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
                    [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
                    
                   self.success([self getResultDicFromDateString:[NSString stringWithFormat:@"%@=%@", [myDateFormatter stringFromDate:[NSDate date]] , [myDateFormatter stringFromDate:[NSDate date]]]]);
                    break;
                }
                    
                case 2:
                {
                    
                    self.success([self getResultDicFromDateString:[self getYesterday]]);
                    break;
                }
                case 3:
                {
                    self.success([self getResultDicFromDateString:[self getFromBeginDayToTodayWith:7]]);
                    break;
                }
                case 4:
                {
                    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
                    [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
                    
                    
                    self.success([self getResultDicFromDateString:[self getMonthBeginAndEndWith:[myDateFormatter stringFromDate:[NSDate date]]]]);
                    break;
                }
                    
                case 5:
                {
                    self.success([self getResultDicFromDateString:[self getLastMonthBeginAndEnd]]);

                    break;
                }
                
                case 6:
                {
                    self.success([self getResultDicFromDateString:[self getFromBeginDayToTodayWith:30]]);
                    break;
                }
                    
                case 7:
                {
                    if (![_endTimeButton.titleLabel.text isEqualToString:@"结束时间"] && ![_startTimeButton.titleLabel.text isEqualToString:@"开始时间"]) {
                        
                        NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
                        [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
                        
                        self.success([self getResultDicFromDateString:[NSString stringWithFormat:@"%@=%@", [myDateFormatter stringFromDate:_startTime], [myDateFormatter stringFromDate:_endTime]]]);
                    }else {
                        
                        [SVProgressHUD showErrorWithStatus:@"请选择开始及结束时间"];
                        return;
                    }
                    
                    break;
                }
                default:
                    break;
            }
            
            [self removeFromSuperview];
            
        }else {
            [SVProgressHUD showErrorWithStatus:@"选择时间区间"];
        }
        
    }else {
        [SVProgressHUD showErrorWithStatus:@"请选择时间类型"];
    }
    
}

//通过时间选择Str获得结果参数
- (NSDictionary *)getResultDicFromDateString:(NSString *) dateString {
    
    ZSBSearchModel *model = _dataList[_timeTypeSelectedButton.tag - 100];
    
    NSDictionary *dic =[NSDictionary dictionaryWithObjectsAndKeys:model.value, @"timeType", dateString, @"timeValue", nil];
    
    return dic;
}


//懒加载
- (NSDate *)startTime {
    if (!_startTime) {
        _startTime = [[NSDate alloc] init];
    }
    return _startTime;
}

- (NSDate *)endTime {
    if (!_endTime) {
        _endTime = [[NSDate alloc] init];
    }
    return _endTime;
}

@end
